package com.ykt.model;

import com.jfinal.plugin.activerecord.Page;
import com.ykt.common.utils.PageUtil;
import com.ykt.common.utils.StringUtil;
import com.ykt.common.utils.page.PageData;
import com.ykt.common.utils.page.PageParam;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Wing
 */
public class Market extends BaseModel<Market> {
    private static final long serialVersionUID = 1L;

    public static final String summary = "summary";
    public static final String province_id = "province_id";
    public static final String cityId = "city_id";
    public static final String district_id = "district_id";
    public static final String address = "address";
    public static final String phone = "phone";
    public static final String logo = "logo";
    public static final String longitude = "longitude";
    public static final String latitude = "latitude";

    public final static Market dao = new Market();


    public PageData<Market> pageFind(PageParam<Map<String, Object>> param) {
        String select = "SELECT m.*, c.*";
        String sqlExceptSelect = " FROM market m" +
                " LEFT JOIN camera_market cm on m.id=cm.market_id" +
                " LEFT JOIN camera c on cm.camera_id=c.id";

        List<Object> paramsVal = new ArrayList<>();
        StringBuilder paramsSql = new StringBuilder("");
        int i = 0;
        for (Map.Entry<String, Object> entry : param.getP().entrySet()) {
            if (entry.getValue() != null) {
                if (i++ == 0) {
                    paramsSql.append(" WHERE ");
                }
                paramsVal.add(entry.getValue());
                paramsSql.append(entry.getKey()).append("=?").append(" and ");
            }
        }

        StringUtil.trimRight(paramsSql, " and ");// 移除最后的“and”字符串

        Page<Market> page = null;
        if (paramsSql.length() == 0) {
            page = this.paginate(param.getPageNo(), param.getPageSize(), select, sqlExceptSelect);

        } else {
            sqlExceptSelect = sqlExceptSelect + paramsSql;
            page = this.paginate(param.getPageNo(), param.getPageSize(), select, sqlExceptSelect, paramsVal.toArray());
        }

        return PageUtil.to(page);
    }

    public List<Market> findAll() {
        String sql = "SELECT m.* FROM market m";

        return super.find(sql);
    }

}
